package com.gcu.drivingschool.controller;

import com.gcu.drivingschool.common.utils.FileUtil;
import com.gcu.drivingschool.domain.vo.Result;
import com.qiniu.common.QiniuException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;

/**
 * 上传文件控制器
 * @author zzr
 * @create 2024-05-10-20:05
 */
@Tag(name = "上传文件控制器", description = "上传文件控制器")
@RestController
@RequestMapping("/api/uploads")
public class UploadController {
    /**
     * 上传文件
     * @param file
     * @return
     * @throws IOException
     */
    @Parameter(name = "file", description = "文件", in = ParameterIn.QUERY, required = true,schema = @Schema(type = "string", format = "binary"))
    @Operation(summary = "上传文件", description = "上传文件到云服务器，返回可访问url")
    @PostMapping
    public Result upload(@NotNull MultipartFile file){
        String url = null;
        try {
            url = FileUtil.upload(file);
        } catch (IOException e) {
            return Result.fail("上传失败");
        }
        return Result.success("上传成功",url);
    }

    /**
     * 删除文件
     * @param url
     * @return
     * @throws IOException
     */
    @Parameter(name = "url", description = "云服务文件url", in = ParameterIn.QUERY, required = true)
    @Operation(summary = "删除文件", description = "删除文件")
    @DeleteMapping
    public Result del(@NotEmpty String url){
        try {
            FileUtil.del(url);
        } catch (QiniuException e) {
            return Result.fail("删除失败");
        }
        return Result.success("删除成功");
    }
}
